package org.jeecg.modules.engineering.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.engineering.entity.EquipFaceInfo;
import org.jeecg.modules.engineering.entity.EquipFaceRecord;
import org.jeecg.modules.engineering.service.IEquipFaceInfoService;
import org.jeecg.modules.engineering.service.IEquipFaceRecordService;
import org.jeecg.modules.engineering.service.IEquipFaceUserService;
import org.jeecg.modules.engineering.service.IEquipTelpoFaceService;
import org.jeecg.modules.engineering.entity.EquipFaceUser;
import org.jeecg.modules.system.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EquipTelpoFaceServiceImpl implements IEquipTelpoFaceService {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Autowired
    private IEquipFaceInfoService equipFaceInfoService;

    @Autowired
    private IEquipFaceUserService equipFaceUserService;

    @Autowired
    private IEquipFaceRecordService equipFaceRecordService;
    /**
     * 查询设备列表
     * @param sn
     */
    @Override
    public Result queryFaceEquipList(String sn){
        String url = CommonConstant.TELPOFACE_BASE_URL+CommonConstant.TELPOFACE_GETDEVICEINFO;
        Map<String, Object> map= Maps.newHashMap();
        map.put("SN",sn); //设备SN
        JSONObject resultJson = restTemplateUtil.postForEntity(map,url,null);
        List<EquipFaceInfo> infoList = new ArrayList<>();
        if(resultJson != null  && "00".equals(resultJson.getString("errCode"))){
            System.out.println("查询设备成功");
            Map<String,EquipFaceInfo> oldInfoMap = new HashMap<>();
            //开始查询本系统设备数据，并组装成map
            if(StringUtils.isNotBlank(sn)){
                EquipFaceInfo info = equipFaceInfoService.selectByEquipSn(sn);
                oldInfoMap.put(info.getEquipSn(),info);
            }else{
                List<EquipFaceInfo> infos = equipFaceInfoService.list();
                oldInfoMap = infos.stream().collect(Collectors.toMap(EquipFaceInfo::getEquipSn,equipFaceInfo -> equipFaceInfo));
            }
            JSONArray data = resultJson.getJSONArray("data");
            if(data != null && data.size() > 0){
                for(int i = 0 ;i < data.size() ;i++){
                    JSONObject json = data.getJSONObject(i);
                    String newSn = json.getString("SN");
                    EquipFaceInfo info;
                    if(oldInfoMap.containsKey(newSn)){
                        info = oldInfoMap.get(newSn);
                    }else{
                        info = new EquipFaceInfo();
                    }
                    info.setDevIp(json.getString("devIP"));
                    info.setEquipSn(json.getString("SN"));
                    info.setOnline(json.getInteger("online"));
                    info.setOrgId(json.getString("orgId"));
                    info.setSwipeCardCount(json.getInteger("swipeCardCount"));
                    info.setUserCount(json.getInteger("userCount"));
                    info.setVersion(json.getString("version"));
                    info.setLastTime(json.getDate("lastTime"));
                    infoList.add(info);
                }
                if(infoList.size() > 0){
                    equipFaceInfoService.saveOrUpdateBatch(infoList);
                }
                return Result.ok("查询成功");
            }else{
                log.info("查询成功，数据为空");
                return Result.ok("查询成功，数据为空");
            }
        }else{
            log.info("查询设备列表失败");
            return Result.error("查询设备列表失败");
        }
    }
    /**
     * 调用天波人脸识别平台的添加/修改人员
     * @param users
     */
    @Override
    public Result addOrUpdateUser(String sn, List<EquipFaceUser> users){
        String url = CommonConstant.TELPOFACE_BASE_URL+CommonConstant.TELPOFACE_DOWNUSER;
        if(users == null){
            return Result.error("人员列表为空");
        }
        if(users.size() > 10){
            //通过触发同步人员接口的方式添加或者修改人员
            url = CommonConstant.TELPOFACE_BASE_URL+CommonConstant.TELPOFACE_SENDCONTROL;
        }else{
            Map<String, Object> map= Maps.newHashMap();
            long taskId = getTaskId();
            map.put("SN",sn); //设备SN
            map.put("taskId",taskId);
            List<Map<String, Object>> paramsList = new ArrayList<>();
            for (EquipFaceUser user : users){
                Map<String, Object> userMap = Maps.newHashMap();
                userMap.put("pin",user.getPin());
                userMap.put("name",user.getName());
                userMap.put("photo",user.getPhoto());
                userMap.put("cardid",user.getCardId());
                userMap.put("validPeriodStart",user.getValidPeriodStart());
                userMap.put("validPeriodEnd",user.getValidPeriodEnd());
                userMap.put("ruleId",user.getRuleId());
                userMap.put("userType",user.getUserType());
                userMap.put("rightno",user.getRightNo());
                userMap.put("phone",user.getPhone());
                user.setEquipSn(sn);
                user.setLastTaskId(taskId);
                paramsList.add(userMap);
            }
            map.put("Data",paramsList);
            JSONObject resultJson = restTemplateUtil.postForEntity(map,url,null);
            if(resultJson != null  && "00".equals(resultJson.getString("errCode"))){
                log.info("添加/修改人员成功");
                equipFaceUserService.saveBatch(users);
                return Result.ok("添加/修改人员成功");
            }else{
                log.info("添加修改人员失败");
                return Result.ok("添加/修改人员成功");
            }
        }
        return Result.ok();
    }

    @Override
    public Result<String> acceptFaceEventRecords(JSONObject jsonRecord) {
        String sn = jsonRecord.getString("SN");
        if(StringUtils.isBlank(sn)){
            return Result.error("sn为空");
        }
        Integer action = jsonRecord.getInteger("action");
        JSONArray data = jsonRecord.getJSONArray("data");
        if(data != null && data.size() > 0){
            List<EquipFaceRecord> records = new ArrayList<>();
            for(int i = 0;i < data.size(); i++){
                JSONObject json = data.getJSONObject(i);
                EquipFaceRecord record = new EquipFaceRecord();
                record.setEquipSn(sn);
                record.setAction(action);
                //开始设置刷脸人员属性
                record.setRecordId(json.getString("recordid"));
                record.setOrgId(json.getString("orgid"));
                record.setPin(json.getString("pin"));
                record.setName(json.getString("name"));
                record.setPhoto(json.getString("photo"));
                record.setCardId(json.getString("cardid"));
                record.setVerifyType(json.getInteger("verifytype"));
                record.setTime(json.getDate("time"));
                record.setOutType(json.getInteger("outtype"));
                record.setRightNo(json.getInteger("rightno"));
                record.setPhone(json.getString("phone"));
                //开始设置刷脸人员身份证信息
                JSONObject idCard = json.getJSONObject("idCard");
                if(idCard != null){
                    record.setIdCardName(idCard.getString("name"));
                    record.setIdCardSex(idCard.getInteger("sex"));
                    record.setIdCardNation(idCard.getString("nation"));
                    record.setIdCardBorn(idCard.getString("born"));
                    record.setIdCardAddress(idCard.getString("address"));
                    record.setIdCardApartment(idCard.getString("apartment"));
                    record.setIdCardPeriod(idCard.getString("period"));
                    record.setIdCardNo(idCard.getString("no"));
                    record.setIdCardCountry(idCard.getString("country"));
                    record.setIdCardCnName(idCard.getString("cn_name"));
                    record.setIdCardVersion(idCard.getString("Idcard_version"));
                    record.setIdCardType(idCard.getString("card_type"));
                    record.setIdCardPhoto(idCard.getString("photo"));
                }
                records.add(record);
            }
            equipFaceRecordService.saveBatch(records);
            return Result.ok();
        }else{
            Result.ok("数据为空");
        }
        return null;
    }

    public long getTaskId(){
        return System.currentTimeMillis();
    }
}
